"""

.. module:: a2pspear_servicetest
.. moduleauthor:: @author: 

The purpose of this module is ... 

Note: For this to work successfully the A2P service must be disabled. This can 
      be done by setting 'term:base/runtime/active' to 'False' in a2p_service.xml. 
   
.. seealso:: modules :mod:`<module>`

*Constants*:
.. data:: constant_1
        
    constant_1 is used for ......
        
.. data:: constant_2
        
    constant_2 is used for ......
"""

# Imports
#
import logging
import unittest
import urlparse
from datetime import datetime
import uuid

from datastore.database import DataStore
from datastore.resource import Resource
from datastore.spaces import Spaces
from datastore.uri import Uri
from runtime.rt import Runtime
from runtime.node import LoggingLevels
from runtime.nodelogger import NodeLogger

# Constants
#

# Classes
#

class A2PSpearServiceTest(unittest.TestCase):
    """This class is a unit test for A2PTask. 

    *Usage examples*::

        example code

    *Common Arguments for Class methods*:
        <arguments>
    
    *Audience*:
        <audience>
    
    *Constants*:
        .. data:: constant_1
        
            constant_1 is used for ......
        
        .. data:: constant_2
        
            constant_2 is used for ......
    """

    
    @staticmethod
    def init():
        
        A2PSpearServiceTest.datastore = DataStore(filename="U:\\yarra-node-test\\eplanning.datastore")
        A2PSpearServiceTest.spaces = Spaces()
        
        # Initialise Runtime and Spaces. This results in the loading of spaces' 
        # namespace bindings.
        #
        rt = Runtime(A2PSpearServiceTest.datastore)
        rt.spaces = A2PSpearServiceTest.spaces
        rt.start_service_manager_and_config_service()
        
#        A2PSpearServiceTest.a2pspear_service_uri = Uri('internal:base/services-list/a2pspear_service/a2pspearrequest')
        A2PSpearServiceTest.a2pspear_service_uri = Uri('internal:eplanning/spear/a2pspear_service/a2pspearrequest')
        A2PSpearServiceTest.SpearReferenceNumber = ""
        A2PSpearServiceTest.SpearAppToken = ""
        A2PSpearServiceTest.sid004_dict = {}
        
        A2PSpearServiceTest.logger = NodeLogger.getLogger('eplanning.spear.a2pspear_servicetest.A2PSpearServiceTest')
        
    def setUp(self):
        """This function initialises the unit test.
        """
        
        self.logger = A2PSpearServiceTest.logger
        
        self.spaces = A2PSpearServiceTest.spaces
        self.a2pspear_service_uri = A2PSpearServiceTest.a2pspear_service_uri
        
        self.SpearReferenceNumber = A2PSpearServiceTest.SpearReferenceNumber
        self.SpearAppToken = A2PSpearServiceTest.SpearAppToken
        
        self.sid002b_dict_list = []
        self.sid004_dict = A2PSpearServiceTest.sid004_dict
        self.sid072a_dict = {}
        
    def tearDown(self):
        """This function finalises the unit test.
        
        :param param_1: <class> or <type>
        :param param_2: <class> or <type>
        :rtype: <return type>
        """
        
        self.logger.log(logging.DEBUG, "===================== tearDown()")
    
    def test_get_0(self):
        """This function tests a request for the send Accept/Reject (REJECT). 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting Accept/Reject (REJECT)")
        
        args_dict = {}
        args_dict["spearReferenceNumber"] = "S008090V"
        args_dict["spearAppToken"] = "8162"
        args_dict["reject_reason"] = "This is a rejection reason from A2PSpearServiceTest."
        
        # create the request Resource - "Current Application List" (sid002b)
        #
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/send-acceptreject-reject")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", args_dict)
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        rs = self.spaces.get(response_uri)
        
        self.logger.log(logging.DEBUG, "===================== sid002b (%s)" % (rs.pretty_print()))
        
        self.assertEqual(True, True)
    
    def test_get_1(self):
        """This function tests a request for the Spear application list. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting sid002b")
        
        # create the request Resource - "Current Application List" (sid002b)
        #
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/currentapplicationlist")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", {})
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        rs = self.spaces.get(response_uri)
        
        self.sid002b_dict_list = rs.get_var("sid002b_dict_list")
        
        # Note: The 'SpearReferenceNumber' is the same as 'sid002b_spear_ref'.
        #       The 'SpearAppToken' is the same as 'sid002b_app_id'.      
        #
        if (len(self.sid002b_dict_list) > 0):
            A2PSpearServiceTest.SpearReferenceNumber = self.sid002b_dict_list[0]["sid002b_spear_ref"]
            A2PSpearServiceTest.SpearAppToken = self.sid002b_dict_list[0]["sid002b_app_id"]
        
        self.logger.log(logging.DEBUG, "===================== sid002b (%s)" % (rs.pretty_print()))
        
        self.assertEqual(True, True)
        
    def test_get_2(self):
        """This function tests a request for the Spear application details. 
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting sid004")
        
        # Note: The 'SpearAppToken' is the same as 'sid002b_app_id'.
        #
#        SpearReferenceNumber = "S005655E"
#        SpearReferenceNumber = "S005896E"
#        SpearReferenceNumber = "S005446B"
#        SpearReferenceNumber = "S006738J"
#        SpearReferenceNumber = "S007533P"
#        SpearReferenceNumber = "S007307J"
        SpearReferenceNumber = A2PSpearServiceTest.SpearReferenceNumber
        
        # create the request Resource - "Application Details" (sid004)
        # - this depends on "Application List"
        #
        args_dict = {}
#        args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
        args_dict["spearReferenceNumber"] = SpearReferenceNumber
#        args_dict["spearAppToken"] = self.SpearAppToken
        
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/applicationdetails")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", args_dict)
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        rs = self.spaces.get(response_uri)
        
        A2PSpearServiceTest.sid004_dict = rs.get_var("sid004_dict")
        
        self.logger.log(logging.DEBUG, "===================== sid004 (%s)" % (rs.pretty_print()))
        
        self.assertEqual(False, False)
        
    def test_get_3(self):
        """This function tests requests for the Spear application attachments. 
        """
        
        # Note: From the "Application Details" (sid004) page the documents clickthru as follows:
        #
        #       Applicant Contact:
        #       - Cultural Heritage Management Plan requirements
        #         > None
        #       - Copy of Title
        #         > sid005a
        #           > PDF
        #       - Plan of Elevations & Sections
        #         > sid005a
        #           > PDF
        #       - Site plan (existing)
        #         > sid005a
        #           > PDF
        #       - Site plan (proposed)
        #         > sid005a
        #           > PDF
        #       - Application for Planning Permit
        #         > sid005a
        #           > sid006a
        #       - Planning Property Report
        #         > services.land.vic.gov.au
        #
        #       Responsible Authority:
        #       - Application Acceptance / Rejection
        #         > sid005a
        #       - Other Document Type
        #         > sid005a
        #           > PDF
        #       - Responsible Authority Reference Number
        #         > sid072a
        #       - Modify Application Details
        #         > None
        #
        #       Referral Authorities:
        #
        #       Online Objectors:
        #
        #       VCAT:
        #
                
        for sid004_attachment_dict in self.sid004_dict["sid004_attachment_dict_list"]:
            if ("sid004_doctype" in sid004_attachment_dict) and ("document_url" in sid004_attachment_dict):
                if (sid004_attachment_dict["sid004_doctype"] == "Responsible Authority Reference Number"):
                    # Request sid072a.
                    #
                    self.logger.log(logging.DEBUG, "===================== Requesting sid072a (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                            
                    url = sid004_attachment_dict["document_url"]
                    url_parts = urlparse.urlparse(str(url))
            
                    # create the request Resource - "Application Document" (sid005a)
                    # - this depends on "Application Details"
                    #
                    args_dict = {}
                    args_dict["documentUrlPath"] = url_parts.path
                    args_dict["documentUrlQuery"] = url_parts.query
                    args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                    
                    rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                    rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument-responsibleauthorityreferencenumber")
                    rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                    rs.set_var("arguments_dict", args_dict)
                    response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                    rs = self.spaces.get(response_uri)
                    
#                    self.sid072a_dict = rs.get_var("sid072a_dict")
                    
                    self.logger.log(logging.DEBUG, "===================== sid072a (%s)" % (rs.pretty_print()))
                    
                elif (sid004_attachment_dict["sid004_doctype"] == "Referral Request"):
                    # Request sid061a.
                    #
                    self.logger.log(logging.DEBUG, "===================== Requesting sid061a (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                    
                    url = sid004_attachment_dict["document_url"]
                    url_parts = urlparse.urlparse(str(url))
            
                    # create the request Resource - "Application Document" (sid005a)
                    # - this depends on "Application Details"
                    #
                    args_dict = {}
                    args_dict["documentUrlPath"] = url_parts.path
                    args_dict["documentUrlQuery"] = url_parts.query
                    args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                    
                    rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                    rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument-referralrequest")
                    rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                    rs.set_var("arguments_dict", args_dict)
                    response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                    rs = self.spaces.get(response_uri)
                    
                    self.logger.log(logging.DEBUG, "===================== sid061a (%s)" % (rs.pretty_print()))
                
                elif (sid004_attachment_dict["sid004_doctype"] == "RA Response"):
                    # Request sid005a.
                    #
                    url = sid004_attachment_dict["document_url"]
                    url_parts = urlparse.urlparse(str(url))
                    
                    self.logger.log(logging.DEBUG, "===================== Requesting sid005a (%s)(%s)" % (sid004_attachment_dict["sid004_doctype"], url))
                    
                    # create the request Resource - "Application Document" (sid005a)
                    # - this depends on "Application Details"
                    #
                    args_dict = {}
                    args_dict["documentUrlPath"] = url_parts.path
                    args_dict["documentUrlQuery"] = url_parts.query
                    args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                    
                    rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                    rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument")
                    rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                    rs.set_var("arguments_dict", args_dict)
                    response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                    rs = self.spaces.get(response_uri)
                    
                    self.logger.log(logging.DEBUG, "===================== sid005a (%s)" % (rs.pretty_print()))
                    
                    if (len(sid004_attachment_dict["sid004_complementary_doctype_link_dict_list"]) > 0):
                        for sid004_complementary_doctype_link_dict in sid004_attachment_dict["sid004_complementary_doctype_link_dict_list"]:
                            self.logger.log(logging.DEBUG, "===================== Complementary document (%s)(%s)" % (sid004_complementary_doctype_link_dict["title"], sid004_complementary_doctype_link_dict["url"]))
                            
                            if (sid004_complementary_doctype_link_dict["title"] == "(View RA Comments)"):
                                # Request sid075c.
                                #
                                url = sid004_complementary_doctype_link_dict["url"]
                                url_parts = urlparse.urlparse(str(url))
                        
                                # create the request Resource - "Application Document" (sid005a)
                                # - this depends on "Application Details"
                                #
                                args_dict = {}
                                args_dict["documentUrlPath"] = url_parts.path
                                args_dict["documentUrlQuery"] = url_parts.query
                                args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                                
                                rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                                rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument-racomments")
                                rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                                rs.set_var("arguments_dict", args_dict)
                                response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                                rs = self.spaces.get(response_uri)
                                
                                self.logger.log(logging.DEBUG, "===================== sid075c (%s)" % (rs.pretty_print()))
                
                elif (sid004_attachment_dict["sid004_doctype"] == "Assess Proposed Changes to Application"):
                    self.logger.log(logging.DEBUG, "===================== Ignoring (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                    
                    # Request sid046b.
                    #
                
                elif (sid004_attachment_dict["sid004_doctype"] == "Planning Property Report"):
                    # Non-Spear request.
                    #
                    self.logger.log(logging.DEBUG, "===================== Making non-Spear request (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                
                elif (len(sid004_attachment_dict["document_url"]) == 0):
                    self.logger.log(logging.DEBUG, "===================== Ignoring (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                
                else:
                    # Request sid005a.
                    #
                    url = sid004_attachment_dict["document_url"]
                    url_parts = urlparse.urlparse(str(url))
                    
                    self.logger.log(logging.DEBUG, "===================== Requesting sid005a (%s)(%s)" % (sid004_attachment_dict["sid004_doctype"], url))
                    
                    # create the request Resource - "Application Document" (sid005a)
                    # - this depends on "Application Details"
                    #
                    args_dict = {}
                    args_dict["documentUrlPath"] = url_parts.path
                    args_dict["documentUrlQuery"] = url_parts.query
                    args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                    
                    rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                    rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument")
                    rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                    rs.set_var("arguments_dict", args_dict)
                    response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                    rs = self.spaces.get(response_uri)
                    
                    self.logger.log(logging.DEBUG, "===================== sid005a (%s)" % (rs.pretty_print()))
                    
                    # Possibilities from this point are:
                    # - PDF
                    # - sid006a
                    # - None
                    #
                    
                    if (rs.has_var("sid005a_dict")):
                        sid005a_dict = rs.get_var("sid005a_dict")
                        self.logger.log(logging.DEBUG, "--------------------- sid005a_dict (%s)" % sid005a_dict)
                        
                        if (sid005a_dict["sid005a_current_document_doctype"].startswith("Application for")):
                            # This gets:
                            # - Application for Planning Permit
                            # - Application for Certification
                            # - Application for Planning Permit and Certification
                            #
                            # Request sid006a.
                            #
                            self.logger.log(logging.DEBUG, "===================== Requesting sid006a (%s)(%s)" % (sid005a_dict["sid005a_current_document_doctype"], url))
                            
                            url = sid005a_dict["document_url"]
                            url_parts = urlparse.urlparse(str(url))
                            
                            args_dict = {}
                            args_dict["documentUrlPath"] = url_parts.path
                            args_dict["documentUrlQuery"] = url_parts.query
                            args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                            args_dict["documentType"] = sid005a_dict["sid005a_current_document_doctype"]
                            
                            # create the request Resource - "Application Document Artefact" (sid006a)
                            # - this depends on "Application Document" (sid005a)
                            #
                            rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                            rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument-applicationforplanningpermit")
                            rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                            rs.set_var("arguments_dict", args_dict)
                            response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                            rs = self.spaces.get(response_uri)
                            
                            self.logger.log(logging.DEBUG, "===================== sid006a (%s)" % (rs.pretty_print()))
                            
                        elif (sid005a_dict["sid005a_current_document_doctype"] == "Application Acceptance / Rejection"):
                            self.logger.log(logging.DEBUG, "===================== Have just processed (%s). No further pages." % (sid005a_dict["sid005a_current_document_doctype"]))
                        
                        # Not all sid005a documents have attachments.
                        #
                        elif (sid005a_dict.has_key("document_url") is True):
                            if (len(sid005a_dict["document_url"]) == 0):
                                self.logger.log(logging.DEBUG, "===================== Ignoring (%s)" % (sid004_attachment_dict["sid004_doctype"]))
                            
                            else:
                                # Request PDF.
                                #
                                url = sid005a_dict["document_url"]
                                url_parts = urlparse.urlparse(str(url))
                                
                                self.logger.log(logging.DEBUG, "===================== Requesting PDF (%s)(%s)" % (sid005a_dict["sid005a_current_document_doctype"], url))
                                
                                args_dict = {}
                                args_dict["documentUrlPath"] = url_parts.path
                                args_dict["documentUrlQuery"] = url_parts.query
                                args_dict["spearReferenceNumber"] = self.SpearReferenceNumber
                                args_dict["documentType"] = sid005a_dict["sid005a_current_document_doctype"]
                                
                                # create the request Resource - "Application Document (PDF)"
                                # - this depends on "Application Document" (sid005a)
                                #
                                rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
                                rs.set_var('a2pspear:request/uri', "spear:request/applicationdocument-pdf")
                                rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
                                rs.set_var("arguments_dict", args_dict)
                                response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
                                rs = self.spaces.get(response_uri)
                                    
#                                    self.logger.log(logging.DEBUG, "===================== PDF (%s)" % (rs.pretty_print()))
                                
        
        self.assertEqual(True, True)

    def test_get_4(self):
        """This function tests a request for the Spear RA list.
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting RA list")
        
        # create the request Resource - "Get User List"
        # - this has no dependencies except login.
        #
        
        args_dict = {}
        args_dict["user_role_council"] = "85:RESPONSIBLE_AUTHORITY"
        args_dict["user_role_administrator"] = "85:LOCAL_ADMINISTRATOR"
        
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/ras")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", args_dict)
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        response_rs = self.spaces.get(response_uri)
        
        self.logger.log(logging.DEBUG, "===================== RA List (%s)" % (response_rs.pretty_print()))
        
        self.assertEqual(False, False)
    
    def test_get_5(self):
        """This function tests a request for the Spear user list.
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting user list")
        
        # create the request Resource - "Get User List"
        # - this has no dependencies except login.
        #
        
        args_dict = {}
        args_dict["user_role_council"] = "85:RESPONSIBLE_AUTHORITY"
        args_dict["user_role_administrator"] = "85:LOCAL_ADMINISTRATOR"
        
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/users")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", args_dict)
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        response_rs = self.spaces.get(response_uri)
        
        self.logger.log(logging.DEBUG, "===================== User List (%s)" % (response_rs.pretty_print()))
        
        self.assertEqual(True, True)
        
    def test_get_6(self):
        """This function tests a request for the Spear activity log.
        """
        
        self.logger.log(logging.DEBUG, "===================== Requesting activity log")
        
        # create the request Resource - "Get Activity Log"
        # - this has no dependencies except login.
        #
        
        dt_now = datetime.now()
        dt_midnight = datetime(dt_now.year, dt_now.month, dt_now.day, 0, 0, 0)

        args_dict = {}
        args_dict["startDate"] = dt_midnight.strftime("%Y%m%dT%H%M%S")
        
        rs = Resource(type='term:eplanning/spear/a2pspear_service/a2pspearrequest')
        rs.set_var('a2pspear:request/uri', "spear:request/activitylog")
        rs.set_var('a2pspear:request/uuid', str(uuid.uuid4()))
        rs.set_var("arguments_dict", args_dict)
        response_uri = self.spaces.put(self.a2pspear_service_uri, rs)
        rs = self.spaces.get(response_uri)
                
        self.logger.log(logging.DEBUG, "===================== Activity Log (%s)" % (rs.pretty_print()))
        
        self.assertEqual(True, True)
        
if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    A2PSpearServiceTest.init()
    unittest.main()